import re
from typing import List, Dict, Any
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain_openai import ChatOpenAI
import os
import sys

OPENAI_API_KEY = "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"

ESSAY_EVALUATION_PROMPT = """
根据下列信息，评估并提供作文的反馈：
题目：{essay_topic}
作文内容：{essay_text}
作者英语能力评价：{learning_ability_evaluation}
这是一个对于学生作文的评分示例：
作文题目: 描述一次难忘的旅行经历
作文内容：I went to the store.
作者英语能力评价：用户英语能力较弱，需要提供基础的写作指导。
{{
  "content": {{
    "score": 0,
    "comment": "作文内容未能紧扣题目要求描述一次难忘的旅行经历，而是提到了去商店的经历，这与题目要求不符。因此内容得分极低。"
  }},
  "organization": {{
    "score": 0,
    "comment": "由于作文内容极为简短，没有展现出任何文章结构，因此组织结构得分也很低。"
  }},
  "grammar": {{
    "score": 0,
    "comment": "虽然提供的句子在语法上是正确的，但内容极短，且为扣题，故评分极低"
  }},
  "detailed_suggestions": "鉴于作者英语能力较弱，建议从基础的句子结构学习开始。学习如何构建简单句和常用句型。练习描述日常活动或经历，如一次到商店的旅行，然后逐步增加描述的复杂性。使用基础的英语教材或加入初级英语写作班，逐步提高写作能力。"
}}
基于作文的内容、组织结构、语法及作者的英语能力水平，以以下JSON格式提供详细评分和建议：

{{
  "content": {{
    "score": "在10分满分中，内容的得分根据学生作文内容与题目要求的符合程度来决定。如果内容与题目完全无关，则得分极低。",
    "comment": "评价应基于内容是否紧扣主题、观点是否清晰、论据是否充分。如果学生的作文内容与题目要求无关或相关性极低，应给出低分并具体指出缺失的部分。"
  }},
  "organization": {{
    "score": "在10分满分中，组织结构的得分应根据文章结构的合理性、段落的清晰性、逻辑的流畅性来评定。如果文章缺乏明确的结构，得分应低。",
    "comment": "具体评价文章的组织是否合理，段落是否有序，信息是否逻辑连贯。对于结构混乱无逻辑的情况应明确指出，并给予低分。"
  }},
  "grammar": {{
    "score": "在10分满分中，语法得分应基于文中的语法正确性、用词的恰当性及标点的准确使用来评定。即便语句简单，如存在语法错误也应相应扣分。",
    "comment": "评价中应指出语法错误、拼写错误及任何标点使用错误，即使是简单句子也必须符合语法规则。"
  }},
  "detailed_suggestions": "基于作者的英语能力提供针对性的改进建议，旨在帮助提高写作水平。建议应包括写作技巧的提升、语法和词汇使用的具体改进点。也可以提供具体对于某一句话的修改意见"
}}
请确保您的评价和建议既准确又有益，以帮助作者根据其英语水平，有效提升写作技能。
"""

os.environ["http_proxy"] = "http://127.0.0.1:10808"
os.environ["https_proxy"] = "http://127.0.0.1:10808"


def evaluate_essay(
    essay_text: str,
    essay_topic: str,
    learning_ability_evaluation: str,
    question_score: int,
):
    """
    This function evaluates an essay based on its content, organization, and grammar. It uses the OpenAI API to
    generate an evaluation result, which is then used to calculate the total score of the essay.

    Args:
        essay_text (str): The text of the essay to be evaluated.
        essay_topic (str): The topic of the essay.
        learning_ability_evaluation (str): The evaluation of the learning ability.
        question_score (int): The score of the question.

    Returns:
        dict: A dictionary containing the success status, the data of the evaluation, and any error that occurred.
        The dictionary has the following structure:
        {
            "success": True,
            "data": {
                "total_score": int(total_score),
                "content_score": evaluation_result["content"]["score"],
                "content_comment": evaluation_result["content"]["comment"],
                "organization_score": evaluation_result["organization"]["score"],
                "organization_comment": evaluation_result["organization"]["comment"],
                "grammar_score": evaluation_result["grammar"]["score"],
                "grammar_comment": evaluation_result["grammar"]["comment"],
                "detailed_suggestions": evaluation_result["detailed_suggestions"]
            },
            "error": None
        }
        If an exception occurs during the evaluation, the function catches it and returns a dictionary with an
        error message.
    """
    try:
        prompt_template = ChatPromptTemplate.from_template(ESSAY_EVALUATION_PROMPT)
        llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
        json_parser = JsonOutputParser()

        chain = prompt_template | llm | json_parser
        evaluation_result = chain.invoke(
            {
                "essay_text": essay_text,
                "essay_topic": essay_topic,
                "learning_ability_evaluation": learning_ability_evaluation,
            }
        )
        contentScore = float(evaluation_result["content"]["score"])
        structureScore = float(evaluation_result["organization"]["score"])
        syntaxScore = float(evaluation_result["grammar"]["score"])
        # 计算总分
        total_score = contentScore * 0.4 + structureScore * 0.3 + syntaxScore * 0.3
        total_score = total_score * question_score / 10
        # 构造返回结果
        data = {
            "totalScore": int(total_score),
            "contentScore": contentScore,
            "contentComment": evaluation_result["content"]["comment"],
            "structureScore": structureScore,
            "structureComment": evaluation_result["organization"]["comment"],
            "syntaxScore": syntaxScore,
            "syntaxComment": evaluation_result["grammar"]["comment"],
            "detailedSuggestions": str(evaluation_result["detailed_suggestions"]),
        }
        print(str(data))
    except Exception as e:
        print(e)
        # return {"success": False, "data": None, "error": str(e)}


if __name__ == "__main__":

    essay_text = sys.argv[1]
    correct_topic = sys.argv[2]
    learning_ability_evaluation = sys.argv[3]
    question_score = int(sys.argv[4])
    # essay_text = "The sun was just beginning to rise as we set out on our journey. It was a trip I had been eagerly anticipating for months – a trek through the lush greenery of the Amazon rainforest. As we ventured deeper into the wilderness, I couldn't help but marvel at the sheer beauty and untamed majesty of nature surrounding us.\r\n\r\nOur days were filled with thrilling encounters and unforgettable experiences. We navigated through dense foliage, crossed rushing rivers on rickety bridges, and climbed towering trees to catch glimpses of exotic birds and monkeys swinging from branch to branch. Each moment was an adventure, each sight a wonder to behold.\r\n\r\nOne particular memory stands out among the rest – the night we spent camping deep in the heart of the rainforest. As darkness fell and the sounds of the jungle came alive around us, we gathered around a crackling campfire, sharing stories and laughter under a blanket of stars. It was a moment of pure magic, one that will stay with me forever.\r\n\r\nBut amidst the beauty and excitement, there were also challenges to overcome. We faced sweltering heat, relentless mosquitoes, and the occasional downpour that left us drenched to the bone. Yet, each obstacle only served to strengthen our bond as a group and deepen our appreciation for the rugged beauty of the Amazon.\r\n\r\nOne unforgettable journey I embarked on was a trip to the breathtaking landscapes of Iceland. From the moment I set foot on its soil, I was captivated by its raw beauty. We explored volcanic landscapes, glistening glaciers, and cascading waterfalls. The highlight was witnessing the dancing Northern Lights painting the night sky with vibrant hues of green and purple. Each day brought new adventures, from soaking in natural hot springs to hiking along rugged coastlines. But it wasn't just the scenery that left a lasting impression; it was the warmth of the Icelandic people and their rich culture that truly made the trip unforgettable. As I bid farewell to this enchanting land, I carried with me memories that would last a lifetime."
    # correct_topic = "描述一次难忘的旅行经历。"
    # learning_ability_evaluation = 90
    # question_score = 15
    # essay_text = "wobuhui"
    evaluate_essay(
        essay_text, correct_topic, learning_ability_evaluation, question_score
    )
